import React from 'react';
import { connect } from 'dva';
import ColorSelector from '@/components/ColorSelector';
import { CardColor, CardType } from '@/utils/const';
import styles from './style.less';

interface CardFrameSelectorProps {
  data: {
    type: string;
    type2: string;
    type3: string;
  };
  dispatch: Function;
}

let lastType3: any;
const CardFrameSelector: React.FC<CardFrameSelectorProps> = ({ data, dispatch }) => {
  const { type, type2, type3 } = data;

  const getItemClassName = () => {
    return type3 === CardType.lb ? (styles.pele + ' ' + styles.select) : styles.pele;
  };

  const getPeleStyle = () => {
    const typeItem = CardColor.find((item: any) => item?.value?.type2 === type2);
    return { background: `linear-gradient(${typeItem?.color}, ${CardColor[0].color})` };
  };

  const handleTypeChange = (value: any) => {
    if (type3 === CardType.lb && (
      value.type !== CardType.monster
      || value.type2 === CardType.lj
      || value.type2 === CardType.tk
    )) {
      value.type3 = lastType3;
    }

    dispatch({
      type: 'cardData/change-data',
      payload: value,
    })
  };

  const handlePele = () => {
    if (type3 === CardType.lb) {
      dispatch({
        type: 'cardData/change-data',
        payload: { type3: lastType3 },
      })
    } else {
      lastType3 = type3;
      dispatch({
        type: 'cardData/change-data',
        payload: { type: CardType.monster, type3: CardType.lb },
      })
    }
  };

  return (
    <>
      <ColorSelector data={CardColor} onChange={handleTypeChange} />
        {(type === CardType.monster && type2 !== CardType.lj) ?
          (
            <div className={styles['color-item']} onClick={handlePele}>
              <div className={getItemClassName()} style={getPeleStyle()} />
              <span>灵摆</span>
            </div>
          ) : null}
    </>
  );
};

const mapStateToProps = ({ cardData }) => {
  const { data } = cardData;
  return {
    data,
  }
};

export default connect(mapStateToProps)(CardFrameSelector);
